package com.library.servlet.admin;

import com.library.entity.Payrec;
import com.library.service.admin.PayrecService;
import com.library.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/admin/payrec")
public class PayrecServlet extends BaseServlet {

    private final PayrecService payrecService = new PayrecService();
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 显示罚款记录页面
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void fineRecord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取分页参数
        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");
        String keyword = request.getParameter("keyword");
        String startDateStr = request.getParameter("startDate");
        String endDateStr = request.getParameter("endDate");

        // 设置默认值
        int pageNum = 1;
        int pageSize = 5;

        // 解析分页参数
        if (pageNumStr != null && !pageNumStr.isEmpty()) {
            try {
                pageNum = Integer.parseInt(pageNumStr);
                if (pageNum < 1) pageNum = 1;
            } catch (NumberFormatException e) {
                pageNum = 1;
            }
        }

        if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
            try {
                pageSize = Integer.parseInt(pageSizeStr);
                if (pageSize < 1) pageSize = 5;
            } catch (NumberFormatException e) {
                pageSize = 5;
            }
        }

        // 解析日期参数
        Date startDate = null;
        Date endDate = null;
        String dateError = null;

        try {
            if (startDateStr != null && !startDateStr.trim().isEmpty()) {
                startDate = dateFormat.parse(startDateStr.trim());
            }
            if (endDateStr != null && !endDateStr.trim().isEmpty()) {
                endDate = dateFormat.parse(endDateStr.trim());
            }
        } catch (ParseException e) {
            dateError = "日期格式不正确";
        }

        // 验证日期范围
        if (dateError == null && !payrecService.isValidDateRange(startDate, endDate)) {
            dateError = "开始日期不能晚于结束日期";
        }

        List<Payrec> payrecList;
        int totalCount;

        // 根据查询条件决定使用哪个查询方法
        if (dateError != null) {
            payrecList = new java.util.ArrayList<>();
            totalCount = 0;
            request.setAttribute("error", dateError);
        } else if (startDate != null || endDate != null || (keyword != null && !keyword.trim().isEmpty())) {
            // 有筛选条件时使用综合查询
            payrecList = payrecService.searchPayrecsWithFilters(keyword, startDate, endDate, pageNum, pageSize);
            totalCount = payrecService.getSearchCountWithFilters(keyword, startDate, endDate);
        } else {
            // 没有条件时显示所有记录
            payrecList = payrecService.getPayrecListByPage(pageNum, pageSize);
            totalCount = payrecService.getTotalPayrecCount();
        }

        if (payrecList == null) {
            payrecList = new java.util.ArrayList<>();
        }

        // 计算总页数和总金额
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
        if (totalPages < 1) totalPages = 1;

        BigDecimal totalAmount = payrecService.calculateTotalAmount(payrecList);
        if (totalAmount == null) totalAmount = BigDecimal.ZERO;

        // 设置请求属性
        request.setAttribute("payrecList", payrecList);
        request.setAttribute("pageNum", pageNum);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalAmount", totalAmount);

        // 保持搜索条件
        if (keyword != null && !keyword.trim().isEmpty()) {
            request.setAttribute("keyword", keyword);
        }
        if (startDateStr != null && !startDateStr.trim().isEmpty()) {
            request.setAttribute("startDate", startDateStr);
        }
        if (endDateStr != null && !endDateStr.trim().isEmpty()) {
            request.setAttribute("endDate", endDateStr);
        }

        request.getRequestDispatcher("/WEB-INF/admin/fineRecord.jsp").forward(request, response);
    }

    /**
     * 搜索罚款记录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void searchFineRecord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        fineRecord(request, response);
    }

    /**
     * 获取所有罚款记录（不分页）
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void getAllFineRecords(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Payrec> payrecList = payrecService.getPayrecList();
        BigDecimal totalAmount = payrecService.calculateTotalAmount(payrecList);

        if (payrecList == null) {
            payrecList = new java.util.ArrayList<>();
        }
        if (totalAmount == null) {
            totalAmount = BigDecimal.ZERO;
        }

        request.setAttribute("payrecList", payrecList);
        request.setAttribute("totalCount", payrecList.size());
        request.setAttribute("totalAmount", totalAmount);

        request.getRequestDispatcher("/WEB-INF/admin/fineRecord.jsp").forward(request, response);
    }
}